package cn.dckeji.gameBox.controller;

import cn.dckeji.gameBox.common.utils.MD5;
import cn.dckeji.gameBox.common.utils.WXUtils;
import cn.dckeji.gameBox.common.utils.WxUtil;
import cn.dckeji.gameBox.dto.Result;
import cn.dckeji.gameBox.entity.*;
import cn.dckeji.gameBox.service.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.parser.Entity;
import java.util.*;


@RestController
@RequestMapping("/gameBoxApi")
public class GameBoxApi {
    @Autowired
    private LoginlogService loginlogService;
    @Autowired
    private StartboxlogService startboxlogService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private BannerService bannerService;
    @Autowired
    private InfoService infoService;
    @Autowired
    private StartgamelogService startgamelogService;
    @Autowired
    private InformationService informationService;

    /**
     * 添加登录日志
     *
     * @param loginlog
     * @return
     */
    @RequestMapping(value = "addLoginLog", method = RequestMethod.POST)
    public Result addLoginLog(Loginlog loginlog, HttpServletResponse response) { response.setHeader("Access-Control-Allow-Origin", "*");
        Result result = getResult();
        //检查根据当前的openId是否可以获取到用户信息，如果可以 则获取微信名称  如果不能 则添加一个新的用户
        EntityWrapper<Customer> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("code", loginlog.getOpenId());
        Customer customer = customerService.selectOne(entityWrapper);
        String  id="";
        if (customer!=null) {
            if(StringUtils.isNotBlank(customer.getNickName())){
                loginlog.setUserName(customer.getNickName());
            }
            id=customer.getId();
            customer.setLoginTime(new Date());
            boolean updateCustomer=customerService.updateById(customer);
        } else if(customer==null) {
//            id = MD5.generateShortUuid();
            id=new Integer(this.getId()).toString();
            Customer customer1 = new Customer();
            customer1.setCode(loginlog.getOpenId());
            customer1.setId(id);
            customer1.setLoginTime(new Date());
            customer1.setCreateTime(new Date());
            boolean addCustomerResult = customerService.insert(customer1);
            if (!addCustomerResult) {
                return result;
            }
        }
        if(loginlog.getType()==2){
            Integer gameId= loginlog.getGameId();
            Info info=infoService.selectById(gameId);
            info.setCount(info.getCount()+1);
            infoService.updateById(info);
        }
        loginlog.setLoginTime(new Date());
        boolean addResult = loginlogService.insert(loginlog);
        if (addResult) {
            result.setCode(200);
            result.setData(id);
        }
        return result;
    }


private int getId(){
    StringBuilder str=new StringBuilder();//定义变长字符串
    Random random=new Random();
//随机生成数字，并添加到字符串
    for(int i=0;i<8;i++){
        str.append(random.nextInt(10));
    }
//将字符串转换为数字并输出
    int num=Integer.parseInt(str.toString());
    return num;
}



    /**
     * 获取banner图
     *
     * @return
     */
    @RequestMapping(value = "getBanner", method = RequestMethod.POST)
    public Result getBanner(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Result result = getResult();
        List<Banner> bannerList = bannerService.selectList(null);
        result.setCode(200);
        result.setData(bannerList);
        return result;
    }

    /**
     * 获取游戏列表
     *
     * @return
     */
    @RequestMapping(value = "getGameList", method = RequestMethod.POST)
    public Result getGameList(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Result result = getResult();
        //获取一周热门榜
        List<Info> hotInfo = getGameInfoList(1);
        //获取新游畅玩
        List<Info> newInfo = getGameInfoList(2);
        //获取吐血推荐
        List<Info> tuijianInfo = getGameInfoList(3);
        //获取经典必玩
        List<Info> biwanInfo = getGameInfoList(4);
        //获取狂欢精选
        List<Info> jingxuanInfo = getGameInfoList(5);
        //获取全民热玩
        List<Info> rewanInfo = getGameInfoList(6);
        //获取重点突出
        Page<Info> tuchuInfo = getGameInfoPage(7);
        result.setCode(200);
        Map<String, List> maps = new HashMap<>();
        maps.put("hot", hotInfo);
        maps.put("new", newInfo);
        maps.put("tuijian", tuijianInfo);
        maps.put("biwan", biwanInfo);
        maps.put("jingxuan", jingxuanInfo);
        maps.put("rewan", rewanInfo);
        maps.put("tuchu", tuchuInfo.getRecords());
        result.setData(maps);
        return result;
    }

    /**
     * 获取最近在玩的游戏
     *
     * @return
     */
    @RequestMapping(value = "getCurrentGame", method = RequestMethod.POST)
    public Result getCurrentGame(String openId,HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Result result = getResult();
        List<String> currentGameId = startgamelogService.getCurrentGame(openId);
        if(currentGameId!=null&&currentGameId.size()>0){
            EntityWrapper<Info> infoEntityWrapper = new EntityWrapper<>();
            infoEntityWrapper.in("id", currentGameId);
            List<Info> gameList = infoService.selectList(infoEntityWrapper);
            List<Info> resultList=new ArrayList<>();
            for(String id:currentGameId){
                for(Info info:gameList){
                    if(info.getId().toString().equals(id)){
                        resultList.add(info);
                        break;
                    }
                }
            }
            result.setCode(200);
            result.setData(resultList);
        }else{
            result.setCode(200);
        }
        return result;
    }

    /**
     * 更新用户
     *
     * @param openId
     * @param nickName
     * @param nickImg
     * @param sex
     * @param city
     * @param province
     * @return
     */
    @RequestMapping(value = "updateCustomer", method = RequestMethod.POST)
    public Result updateCustomer(String openId, String nickName, String nickImg, String sex, String city, String province, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Result result = getResult();
        EntityWrapper<Customer> customerEntityWrapper = new EntityWrapper<>();
        customerEntityWrapper.eq("code", openId);
        Customer customer = customerService.selectOne(customerEntityWrapper);
        customer.setNickName(nickName);
        customer.setNickImg(nickImg);
        customer.setSex(sex);
        customer.setCity(city);
        customer.setProvince(province);
        if (customer.getAuthTime() == null) {
            customer.setAuthTime(new Date());
        }
        customer.setLoginTime(new Date());
        boolean updateResult = customerService.updateById(customer);
        if (updateResult) {
            result.setCode(200);
        }
        return result;
    }

    @RequestMapping(value = "getInformation", method = RequestMethod.POST)
    public Result getInformation(Integer type, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Result result = new Result();
        result.setCode(500);
        result.setMsg("服务器错误。");
        EntityWrapper<Information> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("type", type);
        Information information = informationService.selectOne(entityWrapper);
        if (information != null) {
            result.setCode(200);
            result.setData(information);
        }
        return result;
    }

    @RequestMapping(value = "getOpenId", method = RequestMethod.GET)
    public Result getOpenId(String code, Startboxlog startboxlog, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Result result = getResult();
        Map<String, String> userOpenId = WXUtils.getUserOpenId(code);
        String openId = userOpenId.get("openId").replaceAll("\"", "");
        if (StringUtils.isNotBlank(openId)) {
            result.setCode(200);
            result.setData(openId);
        }
        return result;
    }

    private Page<Info> getGameInfoPage(Integer type) {
        Page<Info> page = new Page<>();
        page.setSize(4);
        page.setCurrent(1);
        EntityWrapper<Info> hotWrapper = new EntityWrapper<>();
        hotWrapper.eq("typeId", type);
        hotWrapper.eq("state", 1);
        Page<Info> hotPage = infoService.selectPage(page, hotWrapper);
        return hotPage;
    }

    private List<Info> getGameInfoList(Integer type) {
        EntityWrapper<Info> hotWrapper = new EntityWrapper<>();
        hotWrapper.eq("typeId", type);
        hotWrapper.eq("state", 1);
        List<Info> lists = infoService.selectList(hotWrapper);
        return lists;
    }


    /**
     * 初始化result对象
     *
     * @return
     */
    private Result getResult() {
        Result result = new Result();
        result.setCode(500);
        result.setMsg("服务器异常");
        return result;
    }
}
